pub struct Solution {}

impl Solution {
  pub fn num_friend_requests(ages: Vec<i32>) -> i32 {
    let mut ages = ages;
    ages.sort();
    let mut ret = 0;
    let mut i = 0;
    while i < ages.len() {
      let mut step = 1;
      if ages[i] > 14 {
        let t = ages[i] / 2 + 7;
        let mut r = i;
        while r < ages.len() && ages[r] == ages[i] {
          r += 1;
        }
        step = r - i;
        let mut l = 0;
        let mut m = (l + r) / 2; 
        while l < m {
          if t < ages[m] {
            r = m; 
          } else {
            l = m;
          }
          m = (l + r) / 2;
        }
        // println!("{} {} {}", ages[i], t, m);
        if m == 0 && ages[0] > t  {
          ret += (i - m) * step;
        } else if i - m > 1 {
          ret += (i - m - 1) * step;
        }
        ret += step * (step - 1);
      }
      i += step;       
    };
    ret as i32       
  }
}